﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DispatchAssist.Weather.Entities;
using DispatchAssist.Weather.Helper;
using DispatchAssist.Weather.Interfaces;
using System.IO;

namespace DispatchAssist.Weather
{
    public partial class frmDataManage : Form
    {
        #region Properties

        internal WeatherData WeatherData { get { return WeatherDataHelper.WeatherData; } }
        internal IWeatherMapProvider ActiveWeatherProvider { get; private set; }
        internal IWeatherMapType ActiveWeatherMapType { get; private set; }

        #endregion

        #region .Ctor

        public frmDataManage()
        {
            InitializeComponent();
            this.dgvProvider.AutoGenerateColumns = this.dgvAirport.AutoGenerateColumns = this.dgvInfo.AutoGenerateColumns = this.dgvType.AutoGenerateColumns = false;
        }


        #endregion

        #region Events
        private void frmDataManage_Load(object sender, EventArgs e)
        {
            BindingProviders();
            this.dgvAirport.DataSource = WeatherData.Airports;
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tpType)
            {
                if (dgvProvider.SelectedRows.Count != 1)
                {
                    MessageBox.Show("请选择一个数据源");
                    tabControl1.SelectedTab = tpProviders;
                    return;
                }

                ActiveWeatherProvider = dgvProvider.SelectedRows[0].DataBoundItem as WeatherMapProvider;


                RefreshParentTypeDataSource();
                BindingTypes();
            }
            else if (tabControl1.SelectedTab == tpInfo)
            {
                if (dgvType.SelectedRows.Count != 1)
                {
                    MessageBox.Show("请选择一个类型");
                    tabControl1.SelectedTab = tpType;
                    return;
                }
                ActiveWeatherMapType = dgvType.SelectedRows[0].DataBoundItem as WeatherMapType;
                BindingInfos();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            WeatherDataHelper.SaveData(WeatherData);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        #endregion

        #region Provider


        private void tsbNewProvider_Click(object sender, EventArgs e)
        {
            var provider = new WeatherMapProvider
            {
                WeatherProvideID = Guid.NewGuid(),
                Name = ""

            };
            WeatherData.Providers.Add(provider);

            BindingProviders();
        }

        private void tsbDelProvider_Click(object sender, EventArgs e)
        {
            if (this.dgvProvider.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择需要删除的数据源");
                return;
            }

            foreach (DataGridViewRow dr in dgvProvider.SelectedRows)
            {
                var provider = dr.DataBoundItem as WeatherMapProvider;
                if (provider == null)
                    continue;

                WeatherData.Providers.Remove(provider);
            }

            BindingProviders();
        }

        private void BindingProviders()
        {

            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = WeatherData.Providers;
            this.dgvProvider.DataSource = bindingSource;
        }

        #endregion

        #region MapType

        private void tsbNewType_Click(object sender, EventArgs e)
        {
            var type = new WeatherMapType(ActiveWeatherProvider, WeatherMapType.Empty)
            {
                WeatherMapTypeID = Guid.NewGuid(),
                Name = string.Empty,
                MapType = Enums.MapTypes.Unknow
            };

            ActiveWeatherProvider.Types.Add(type);
            ActiveWeatherProvider.AllTypes.Add(type);

            RefreshParentTypeDataSource();


            BindingTypes();
        }

        private void tsbDeleteType_Click(object sender, EventArgs e)
        {
            if (this.dgvProvider.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择需要删除的类型");
                return;
            }

            foreach (DataGridViewRow dr in dgvType.SelectedRows)
            {
                var type = dr.DataBoundItem as WeatherMapType;
                if (type == null)
                    continue;

                ActiveWeatherProvider.Types.Remove(type);
            }

            RefreshParentTypeDataSource();
            //this.dgvType.DataSource = null;//ReBinding
            //this.dgvType.DataSource = ActiveWeatherProvider.Types;

            BindingTypes();

        }

        private void RefreshParentTypeDataSource()
        {
            dgcParentType.DisplayMember = "Name";
            dgcParentType.ValueMember = "Type";
            //var list = this.ActiveWeatherProvider.GetAllTypes().Select(o => new { Name = o.Name, Value = o }).ToList();
            //list.Insert(0, new { Name = WeatherMapType.Empty.Name, Value = WeatherMapType.Empty });
            var list = this.ActiveWeatherProvider.AllTypes.Select(o => new MapTypeEntity { Type = o }).ToList();
            list.Insert(0, new MapTypeEntity { Type = WeatherMapType.Empty });

            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = list;
            this.dgcParentType.DataSource = bindingSource;

        }
        class MapTypeEntity
        {
            public string Name { get { return Type.Name; } }
            public IWeatherMapType Type { get; set; }
        }
        private void BindingTypes()
        {
            //this.dgvType.DataSource = null;//ReBinding
            //this.dgvType.DataSource = ActiveWeatherProvider.Types;
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = ActiveWeatherProvider.AllTypes;
            this.dgvType.DataSource = bindingSource;

        }

        #endregion

        #region MapInfo

        private void tsbNewInfo_Click(object sender, EventArgs e)
        {
            var info = new WeatherMapInfo(ActiveWeatherMapType)
            {
                WeatherMapInfoID = Guid.NewGuid(),
                Name = string.Empty
            };
            ActiveWeatherMapType.Infos.Add(info);

            BindingInfos();
        }

        private void tsbDeleteInfo_Click(object sender, EventArgs e)
        {
            if (this.dgvProvider.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择需要删除的信息");
                return;
            }

            foreach (DataGridViewRow dr in dgvInfo.SelectedRows)
            {
                var info = dr.DataBoundItem as WeatherMapInfo;
                if (info == null)
                    continue;

                ActiveWeatherMapType.Infos.Remove(info);
            }

            BindingInfos();
        }
        private void BindingInfos()
        {
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = new List<IWeatherMapInfo>(ActiveWeatherMapType.Infos);
            this.dgvInfo.DataSource = bindingSource;
        }

        #endregion

        #region Airport

        private void tsbNewAirport_Click(object sender, EventArgs e)
        {
            var airport = new AirportLocation
            {
                AirportLocationID = Guid.NewGuid(),
                Name = string.Empty
            };
            WeatherData.Airports.Add(airport);

            BindingAirports();
        }

        private void tsbDeleteAirport_Click(object sender, EventArgs e)
        {
            if (this.dgvAirport.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择需要删除的机场");
                return;
            }

            foreach (DataGridViewRow dr in dgvAirport.SelectedRows)
            {
                var airport = dr.DataBoundItem as AirportLocation;
                if (airport == null)
                    continue;

                WeatherData.Airports.Remove(airport);
            }

            BindingAirports();
        }


        private void BindingAirports()
        {
            BindingSource bindingSource = new BindingSource();
            bindingSource.DataSource = WeatherData.Airports;
            this.dgvAirport.DataSource = bindingSource;
        }

        #endregion

        private void dgvType_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.ThrowException = false;
        }

        private void btnImportAirports_Click(object sender, EventArgs e)
        {
            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }


            try
            {
                var file = openFileDialog1.FileName;

                StreamReader sr = File.OpenText(file);
                int i = 1;
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var datas = line.Split('\t');
                    WeatherData.Airports.Add(new AirportLocation
                    {
                        AirportCode = datas[3],
                        AirportLocationID = Guid.NewGuid(),
                        LocationX = decimal.Parse(datas[4]),
                        LocationY = decimal.Parse(datas[5]),
                        Name = datas[0]
                    });
                    i++;
                }

                WeatherDataHelper.SaveData(WeatherData);

                MessageBox.Show(string.Format("导入成功，共导入{0}行数据", i));
            }
            catch
            {
                MessageBox.Show("导入失败！");
            }
        }

        private void btnImportCityMapInfo_Click(object sender, EventArgs e)
        {


            if (dgvType.SelectedRows.Count == 0)
            {
                MessageBox.Show("请选择类型");
                return;
            }

            var mapType = dgvType.SelectedRows[0].DataBoundItem as IWeatherMapType;

            if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }


            try
            {
                var file = openFileDialog1.FileName;


                StreamReader sr = File.OpenText(file);
                int i = 1;
                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var datas = line.Split('\t');
                    ActiveWeatherMapType.Infos.Add(new WeatherMapInfo(mapType)
                    {
                        Name = datas[0],
                        WeatherMapInfoID = Guid.NewGuid(),
                        ScaleX = 0.0095m,
                        ScaleY = 0.0091m,
                        InfoID = datas[2].Replace(@"/html/radar/JC_RADAR_", string.Empty).Replace(@"_JB.shtml", string.Empty)///html/radar/JC_RADAR_AZ9200_JB.shtml
                    });
                    i++;
                }

                WeatherDataHelper.SaveData(WeatherData);

                MessageBox.Show(string.Format("导入成功，共导入{0}行数据", i));
            }
            catch
            {
                MessageBox.Show("导入失败！");
            }
        }



    }
}
